package com.yunqi.autovender.view;

import android.app.Dialog;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import com.yunqi.autovender.R;
import com.yunqi.autovender.databinding.DialogSetupBinding;
import com.yunqi.autovender.model.SetupInfo;

import java.io.File;

import google.architecture.common.util.StringUtils;
import google.architecture.common.util.ToastUtils;
import google.architecture.coremodel.callback.ConfirmCallback;
import google.architecture.coremodel.helper.AppConfigHelper;

/**
 * 配置Dialog
 */
public abstract class SetupDialog extends Dialog {
    private Context mContext;
    private SetupInfo mSetupInfo;
    private DialogSetupBinding mBinding;
    private AppConfigHelper mConfigHelper;

    public SetupDialog(@NonNull Context context) {
        this(context, 0);
    }

    public SetupDialog(@NonNull Context context,int from) {
        this(context, R.style.MyDialog,from);

    }
    //来源：1-从主界面 0-设置
    private SetupDialog(@NonNull Context context, int themeResId,int from) {
        super(context, themeResId);
        mContext = context;
        mSetupInfo = new SetupInfo();
        mSetupInfo.autoConfig.set(from==1);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = View.inflate(mContext, R.layout.dialog_setup, null);
        mBinding = DataBindingUtil.bind(view);
        mBinding.setCallback(mConfirmCallback);
        setContentView(view);
        mConfigHelper = new AppConfigHelper(mContext);
        String serverUrl = mConfigHelper.getServerUrl();
        String serialPath = mConfigHelper.getSerialPath();
        String serialPort = mConfigHelper.getSerialPort();
        String timeOut=mConfigHelper.getTimeOut();
        String countDownTime=mConfigHelper.getCountDownTime();
        String printMaxLength=mConfigHelper.getMaxPrintLength();
        mSetupInfo.serverUrl.set(serverUrl);
        mSetupInfo.serialPath.set(serialPath);
        mSetupInfo.serialPort.set(serialPort);
        mSetupInfo.timeOut.set(timeOut);
        mSetupInfo.countDownTime.set(countDownTime);
        mSetupInfo.printMaxLength.set(printMaxLength);
        mBinding.setSetupInfo(mSetupInfo);
        mBinding.editServerUrl.addTextChangedListener(new MyTextWatcher());
        mBinding.editSerialPort.addTextChangedListener(new MyTextWatcher());
        mBinding.editSerialPath.addTextChangedListener(new MyTextWatcher());
        mBinding.editMaxLength.addTextChangedListener(new MyTextWatcher());
        mBinding.editOutStackTimeOut.addTextChangedListener(new MyTextWatcher());
        mBinding.editCountDown.addTextChangedListener(new MyTextWatcher());
        setCanceledOnTouchOutside(false);
    }

    private ConfirmCallback mConfirmCallback = new ConfirmCallback() {

        @Override
        public void onClick(int action) {
            mConfigHelper.saveFirstLauncher(false);
            switch (action) {
                case ConfirmCallback.ACTION_CANCEL:
                    dismiss();
                    break;
                case ConfirmCallback.ACTION_CONFIRM:
                    String serverUrl = mBinding.editServerUrl.getText().toString();
                    if (!TextUtils.equals(serverUrl, mSetupInfo.serverUrl.get())) {
                        if (StringUtils.isHttpUrl(serverUrl)) {
                            mConfigHelper.saveServerUrl(serverUrl);
                        } else {
                            ToastUtils.showShortToast("非法的服务器地址！");
                            return;
                        }
                    }
                    String serialPath = mBinding.editSerialPath.getText().toString();
                    if (!TextUtils.equals(serialPath, mSetupInfo.serialPath.get())) {
                        File file = new File(serialPath);
                        if (file.exists()) {
                            mConfigHelper.saveSerialPath(serialPath);
                        } else {
                            ToastUtils.showShortToast("串口文件不存在！");
                            return;
                        }

                    }
                    String serialPort = mBinding.editSerialPort.getText().toString();
                    if (!TextUtils.equals(serialPort, mSetupInfo.serialPort.get())) {
                        try {
                            Integer.parseInt(serialPort);
                            mConfigHelper.saveSerialPort(serialPort);
                        } catch (NumberFormatException e) {
                            ToastUtils.showShortToast("非法的波特率！");
                            return;
                        }
                    }
                    String strCountDown = mBinding.editCountDown.getText().toString();
                    if (!TextUtils.equals(strCountDown, mSetupInfo.countDownTime.get())) {
                        try {
                            int countDown=Integer.parseInt(strCountDown);
                            mConfigHelper.saveCountDownTime(countDown);
                        } catch (NumberFormatException e) {
                            ToastUtils.showShortToast("输入的值不合法！");
                            return;
                        }
                    }
                    String strTimeOut = mBinding.editOutStackTimeOut.getText().toString();
                    if (!TextUtils.equals(strTimeOut, mSetupInfo.timeOut.get())) {
                        try {
                            int timeOut=Integer.parseInt(strTimeOut);
                            mConfigHelper.saveTimeOut(timeOut);
                        } catch (NumberFormatException e) {
                            ToastUtils.showShortToast("输入的值不合法！");
                            return;
                        }
                    }
                    String strMaxLength = mBinding.editMaxLength.getText().toString();
                    if (!TextUtils.equals(strMaxLength, mSetupInfo.printMaxLength.get())) {
                        try {
                            int maxLength=Integer.parseInt(strMaxLength);
                            mConfigHelper.saveMaxPrintLength(maxLength);
                        } catch (NumberFormatException e) {
                            ToastUtils.showShortToast("输入的值不合法！");
                            return;
                        }
                    }
                    dismiss();
                    onConfigComplied();
                    break;
                case ConfirmCallback.ACTION_SKIP:
                    dismiss();
                    onConfigComplied();
                    break;
            }
        }
    };

    class MyTextWatcher implements TextWatcher {
        @Override
        public void afterTextChanged(Editable s) {
            String serialPort = mBinding.editSerialPort.getText().toString();
            String serverUrl = mBinding.editServerUrl.getText().toString();
            String serialPath = mBinding.editSerialPath.getText().toString();
            String timeOut = mBinding.editOutStackTimeOut.getText().toString();
            String countDown = mBinding.editCountDown.getText().toString();
            String maxLength = mBinding.editMaxLength.getText().toString();
            if (TextUtils.isEmpty(serialPort) || TextUtils.isEmpty(serverUrl) || TextUtils.isEmpty(serialPath)||TextUtils.isEmpty(timeOut)||TextUtils.isEmpty(countDown)||TextUtils.isEmpty(maxLength)) {
                mSetupInfo.needSave.set(false);
                return;
            }
            if (TextUtils.equals(serialPort, mSetupInfo.serialPort.get())
                    && TextUtils.equals(serverUrl, mSetupInfo.serverUrl.get())
                    && TextUtils.equals(serialPath, mSetupInfo.serialPath.get())
                    && TextUtils.equals(timeOut, mSetupInfo.timeOut.get())
                    && TextUtils.equals(countDown, mSetupInfo.countDownTime.get())
                    && TextUtils.equals(maxLength, mSetupInfo.printMaxLength.get())) {
                mSetupInfo.needSave.set(false);
                return;
            }
            mSetupInfo.needSave.set(true);
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }
    }

    /**
     * 配置完成后回调
     */
    public abstract void onConfigComplied();

}
